#include"mystdio.h"
#include<unistd.h>
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
mFILE* mfopen(const char*filename,const char*mode){
  int fd=-1;
    if(*mode=='r'){
   fd= open(filename,O_RDONLY);
}
   else if(*mode=='w'){
   fd= open(filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
}
else if(*mode=='a'){
    fd=open(filename,O_WRONLY|O_CREAT|O_APPEND,0666);
}
mFILE*f=(mFILE*)malloc(sizeof (mFILE));
if(!f){
    close(fd);
    return NULL;
}
f->fd=fd;
f->flag=FLUSH_FULL;
f->cap=1024;
f->size=0;
return f;
}
int  mfwrite(char*str,int num,mFILE*stream){
   memcpy(stream->buffer+stream->size,str,num);
  stream->size+=num;
 int flag=1;
  if(stream->flag==FLUSH_LINE){
    if(stream->size>0&&stream->buffer[stream->size-1]=='\n'){
   flag=write(stream->fd,stream->buffer,stream->size);
      stream->size=0;
      } 
  }
  else if(stream->flag==FLUSH_FULL){
      if(stream->size>stream->cap*9/10){
   flag=write(stream->fd,stream->buffer,stream->size);
   printf("%d",stream->size); 
   stream->size=0;
      }
  }
  return flag;
}
void mfflush(mFILE*stream){
    write(stream->fd,stream->buffer,SIZE);
}
int mfclose(mFILE*stream){
 mfflush(stream);
    return  close(stream->fd);
}
